<template>
  <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" fullscreen
    @cancel="handleCancel" :footer="null" :destroyOnClose="true">
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts" label="适用门店">
          <a-cascader :options="departModel.departTreeOptions" @change="onDepartChange" :showSearch="true"
            expand-trigger="hover" placeholder="" :fieldNames="fieldNames" style="width: 300px"
            v-model="model.selecteddeparts" :disabled="!isEdit" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planNm" label="方案名称">
          <a-input placeholder="" v-model="model.planNm" style="width: 300px" :disabled="!isEdit" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useDesc" label="使用规则说明">
          <a-input placeholder="" v-model="model.useDesc" style="width: 300px" :disabled="!isEdit" />
        </a-form-model-item>
        <a-divider />
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="givePoints" label="消费赠送积分">
          <div>
            <a-switch v-model="aswitch.givePoints" @change="handelSwitch('givePoints')" :disabled="!isEdit" />
          </div>
          <div>
            消费1元=
            <a-input-number v-model="model.givePoints" :min="1" :step="1" :disabled="disabled.givePoints"
              :formatter="limitNumber" :parser="limitNumber" />积分
          </div>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pointsReduce" label="积分抵现">
          <div>
            <a-switch v-model="aswitch.pointsReduce" @change="handelSwitch('pointsReduce')" :disabled="!isEdit" />
          </div>
          <a-row>
            <a-col :span="3">积分使用门槛:</a-col>
            <a-col :span="16">
              <a-radio-group :disabled="disabled.pointsReduce" v-model="model.pointsLess"
                @change="handelRadio('pointsLess')">
                <a-radio :style="radioStyle" value="0">不限制</a-radio>
                <a-radio :style="radioStyle" :value="1">达到
                  <a-input-number :min="1" :step="1" :formatter="limitNumber" :parser="limitNumber" :max="99999"
                    v-model="model.pointsLess1" :disabled="disabled.pointsReduce" />
                  积分可用
                </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">订单金额门槛:</a-col>
            <a-col :span="16">
              <a-radio-group :disabled="disabled.pointsReduce" v-model="model.orderLess"
                @change="handelRadio('orderLess')">
                <a-radio :style="radioStyle" value="0">不限制</a-radio>
                <a-radio :style="radioStyle" :value="1">订单金额达到
                  <a-input-number v-model="model.orderLess1" :min="1" :step="1" :formatter="limitNumber"
                    :parser="limitNumber" :max="99999" :disabled="disabled.pointsReduce" />
                  元开始抵现
                </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="3">抵现金额上限:</a-col>
            <a-col :span="16">
              <a-radio-group :disabled="disabled.pointsReduce" v-model="model.reduceMax"
                @change="handelRadio('reduceMax')">
                <a-radio :style="radioStyle" value="0">不限制</a-radio>
                <a-radio :style="radioStyle" :value="1">每笔订单最多抵现
                  <a-input-number :min="1" :step="1" :formatter="limitNumber" :parser="limitNumber" :max="99999"
                    v-model="model.reduceMax1" :disabled="disabled.pointsReduce" />
                  元
                </a-radio>
                <a-radio :style="radioStyle" :value="2">每笔订单最多抵现
                  <a-input-number :min="1" :step="1" :formatter="limitNumber" :parser="limitNumber" :max="99"
                    v-model="model.reduceMax2" :disabled="disabled.pointsReduce" />
                  %
                  <a-tooltip title="计算时舍去小数位取整">
                    <a-icon type="question-circle" />
                  </a-tooltip>
                </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
          <a-col :md="24" :sm="24">
            <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
              <a-button type="primary" htmlType="submit" @click="handleOk" v-if="isEdit">保存方案</a-button>
              <a-button type="primary" htmlType="submit" @click="disabledForm(false)" v-else>编辑方案</a-button>
            </a-form-model-item>
          </a-col>
        </a-form-model-item>
      </a-form-model>

      <!-- 积分商品 -->
    </a-spin>
  </j-modal>
</template>
  
<script>
import { httpAction, getAction, deleteAction } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'
import { limitNumber, filterObj } from '@/utils/util'

export default {
  name: 'PosPointsPlanModal',
  components: {
  },
  data() {
    return {
      title: '操作',
      visible: false,
      fullscreen: true,
      model: {},
      isEdit: true,
      aswitch: {},
      limitNumber,
      disabled: {
        givePoints: true,
        pointsReduce: true,
      },
      departModel: {
        departTreeOptions: [],
        orgIds: '',
        orgNames: '',
      },
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      radioStyle: {
        display: 'block',
        height: '35px',
        lineHeight: '35px',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        planNm: [{ required: true, message: '必填项' }],
        selecteddeparts: [{ required: true, message: '必填项' }],
        prodScope: [{ required: true, message: '必填项' }],
      },
      url: {
        add: '/marketing/posPointsPlan/add',
        edit: '/marketing/posPointsPlan/edit',
        queryById: '/marketing/posPointsPlan/queryById',
      },
    }
  },
  created() {
    this.loadDepartTree()
  },
  methods: {
    handelSwitch(rule) {
      let checked = this.aswitch[rule]
      this.disabled[rule] = !checked
      if (!checked) {
        this.resetFieldVal(rule, true)
      }
    },
    resetFieldVal(rule, flag) {
      if (flag) {
        this.$set(this.model, rule, '')
      }
      this.$set(this.model, rule + '1', '')
      if (rule == 'reduceMax') {
        this.$set(this.model, rule + '2', '')
      }
    },
    handelRadio(rule) {
      let selected = this.model[rule]
      console.log(rule, '=', selected)
      if (selected == '0') {
        this.resetFieldVal(rule, false)
      } else if (selected == '1') {
        this.$set(this.model, rule + '2', '')
      } else if (selected == '2') {
        this.$set(this.model, rule + '1', '')
      }
    },
    handelRadioProdScope(rule) {
      let selected = this.model[rule]
      if (selected == '0' || selected == '10') {
        this.$set(this.model, 'priceTail', [])
      }
    },
    loadDepartTree() {
      let that = this
      queryDepartTreeList1({ orgTypes: '2' }).then((res) => {
        if (res.success) {
          that.$set(that.departModel, 'departTreeOptions', res.result)
          console.log('departTreeOptions', that.departModel.departTreeOptions)
          that.departModel.departTreeOptions.forEach((x) => {
            x['children'] = [{ title: '全部门店', value: '0' }]
          })
        }
      })
    },
    onDepartChange(value, selectedOptions) {
      console.log('value:', value)
      console.log('selectedOptions:', selectedOptions)
      this.departModel.orgIds = value && value.length > 0 ? value[0] : ''
      this.departModel.orgNames = selectedOptions && selectedOptions.length > 0 ? selectedOptions[0].departName : ''
      this.$set(this.model, 'planNm', this.departModel.orgNames + '的积分方案')
    },
    add() {
      //初始化默认值
      this.edit({})
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.loadDepartTree()
      if (this.model.id) {
        this.disabledForm(false)
        this.getDetail(this.model.id)
      } else {
        this.isEdit = true
      }
    },
    buildDetailModel(result) {
      console.log('result', result)
      this.$set(this.model, 'selecteddeparts', [result.orgIds, '0'])

      let pointsRuleVoList = result.pointsRuleVoList
      if (pointsRuleVoList && pointsRuleVoList.length > 0) {
        //消费送积分
        let rule32 = pointsRuleVoList.filter((x) => x.ruleType == 32)
        if (rule32 && rule32.length > 0) {
          let givePoints = rule32[0]
          this.$set(this.aswitch, 'givePoints', true)
          this.$set(this.model, 'givePoints', givePoints.ruleVal)
        } else {
          this.$set(this.aswitch, 'givePoints', false)
        }

        //积分抵现
        let rule21 = pointsRuleVoList.filter((x) => x.ruleType == 21)
        if (rule21 && rule21.length > 0) {
          this.$set(this.aswitch, 'pointsReduce', true)
        } else {
          this.$set(this.aswitch, 'pointsReduce', false)
        }
        let rule24 = pointsRuleVoList.filter((x) => x.ruleType == 24)
        if (rule24 && rule24.length > 0) {
          let pointsLess = rule24[0]
          if (pointsLess.ruleVal >= 1) {
            this.$set(this.model, 'pointsLess', 1)
            this.$set(this.model, 'pointsLess1', pointsLess.ruleVal)
          } else {
            this.$set(this.model, 'pointsLess', pointsLess.ruleVal)
          }
        }

        //订单金额门槛
        let rule25 = pointsRuleVoList.filter((x) => x.ruleType == 25)
        if (rule25 && rule25.length > 0) {
          let orderLess = rule25[0]
          if (orderLess.ruleVal >= 1) {
            this.$set(this.model, 'orderLess', 1)
            this.$set(this.model, 'orderLess1', orderLess.ruleVal)
          } else {
            this.$set(this.model, 'orderLess', orderLess.ruleVal)
          }
        }

        //抵现金额上限(按照元)
        let rule22 = pointsRuleVoList.filter((x) => x.ruleType == 22)
        if (rule22 && rule22.length > 0) {
          let reduceMax = rule22[0]
          if (reduceMax.ruleVal >= 1) {
            this.$set(this.model, 'reduceMax', 1)
            this.$set(this.model, 'reduceMax1', reduceMax.ruleVal)
          } else {
            this.$set(this.model, 'reduceMax', reduceMax.ruleVal)
          }
        }

        //抵现金额上限(按照百分比)
        let rule26 = pointsRuleVoList.filter((x) => x.ruleType == 26)
        if (rule26 && rule26.length > 0) {
          let reduceMax = rule26[0]
          this.$set(this.model, 'reduceMax', 2)
          this.$set(this.model, 'reduceMax2', reduceMax.ruleVal)
        }
      }

      this.departModel.orgIds = result.orgIds
      this.departModel.orgNames = result.orgNames
    },
    getDetail(id) {
      let that = this
      getAction(this.url.queryById, { id: id }).then((res) => {
        if (res.success) {
          that.buildDetailModel(res.result)
          that.disabledForm(true)
        } else {
          that.$message.warning('获取详情失败')
        }
      })
    },
    close() {
      this.clearAll()
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    clearAll() {
      this.model = {}
      this.aswitch = {}
      this.departModel = {}
      this.disabled = {
        givePoints: true,
        pointsReduce: true,
      }
    },
    buildParam() {
      console.log(this.model)
      let res = {
        success: true,
      }
      let param = {
        id: this.model.id,
        orgIds: this.departModel.orgIds,
        orgNames: this.departModel.orgNames,
        planNm: this.model.planNm,
        useDesc: this.model.useDesc,
      }

      let pointsRuleVoList = []
      param.pointsRuleVoList = pointsRuleVoList
      //消费送积分
      let givePoints = this.model.givePoints
      if (this.aswitch.givePoints) {
        if (!givePoints) {
          this.$message.warning('消费送积分设置不能为空')
          res.success = false
          return res
        }
        pointsRuleVoList.push({
          ruleType: 32,
          ruleVal: givePoints,
        })
      }

      //积分抵现
      if (this.aswitch.pointsReduce) {
        pointsRuleVoList.push({
          ruleType: 21,
          ruleVal: 1,
        })

        //积分使用门槛
        let pointsLess = this.model.pointsLess
        console.log('pointsLess', pointsLess)

        if (pointsLess === undefined || pointsLess === '') {
          this.$message.warning('积分使用门槛设置不能为空')
          res.success = false
          return res
        }
        if (pointsLess == 1) {
          pointsLess = this.model.pointsLess1
        }
        pointsRuleVoList.push({
          ruleType: 24,
          ruleVal: pointsLess,
        })

        //订单金额门槛
        let orderLess = this.model.orderLess
        console.log('orderLess', orderLess)

        if (orderLess === undefined || orderLess === '') {
          this.$message.warning('订单金额门槛设置不能为空')
          res.success = false
          return res
        }
        if (orderLess == 1) {
          orderLess = this.model.orderLess1
        }
        pointsRuleVoList.push({
          ruleType: 25,
          ruleVal: orderLess,
        })

        //抵现金额上限
        let reduceMax = this.model.reduceMax
        let ruleType = '22'
        if (reduceMax == '1') {
          reduceMax = this.model.reduceMax1
        } else if (reduceMax == '2') {
          //按照百分比
          ruleType = '26'
          reduceMax = this.model.reduceMax2
        }
        if (reduceMax === undefined || reduceMax === '') {
          this.$message.warning('抵现金额上限设置不能为空')
          return false
        }
        pointsRuleVoList.push({
          ruleType: ruleType,
          ruleVal: reduceMax,
        })
      }

      console.log('param', param)
      res.param = param
      return res
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          let res = this.buildParam()
          if (!res.success) {
            return false
          }

          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, res.param, method)
            .then((res) => {
              if (res.success) {
                that.model.id = res.result
                that.disabledForm(true)
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              // that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    disabledForm(bool) {
      this.isEdit = !bool
      this.disabled.pointsReduce = bool
      this.disabled.givePoints = bool
      if (!bool) {
        this.disabled.givePoints = !this.aswitch.givePoints
      }
    },
  },
}
</script>
  
<style scoped lang="less">
@import '~@assets/less/common.less';
</style>